package cn.kgc.controller;


import cn.kgc.constants.Constants;
import cn.kgc.constants.ResultEnum;
import cn.kgc.service.SmsLogService;
import cn.kgc.utils.redis.RedisKeyUtils;
import cn.kgc.utils.redis.RedisUtils;
import cn.kgc.utils.redis.ResultUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 短信记录 前端控制器
 * </p>
 *
 * @author qf
 * @since 2022-03-03
 */
@RestController
@RequestMapping("/api/sms")
public class SmsLogController {

    private final RedisUtils redisUtils;
    private final SmsLogService smsLogService;

    public SmsLogController(RedisUtils redisUtils, SmsLogService smsLogService) {
        this.redisUtils = redisUtils;
        this.smsLogService = smsLogService;
    }

    @PostMapping ("/verifyCode")
    public Map<String,String> verifyCode(String phone,String codeType){
        Map<String,String> map=null;
        //1.验证手机号
        if (!phone.matches(Constants.PHONE_REGSTR)){
            ResultUtils.returnFail("手机号异常","1");
            map.put("code","1");
            map.put("msg","手机号异常");
        }
        //2.验证验证码的类型是否正确
        if (!this.checkCodeType(codeType)){
            ResultUtils.returnResult(ResultEnum.FAIL);
//            map.put("code","1");
//            map.put("msg","验证码类型异常");
        }
        //3.验证短信发送频率60s
        if (!this.checkSmsCode(phone,codeType)){
            map.put("code","1");
            map.put("msg","请勿重复发送");
        }
        //4.发送短信
        map=smsLogService.sendSms(phone,codeType);
        return map;
    }
    //验证codeType
    private boolean checkCodeType(String codeType){
        boolean flag=false;
        if (codeType !=null && (codeType.equals(Constants.Sms.TYPE_REGIST_OR_LOGIN)
                ||codeType.equals(Constants.Sms.STATUS_SEND_FAILED)
                ||codeType.equals(Constants.Sms.STATUS_SEND_SUCCESS)
                ||codeType.equals(Constants.Sms.TYPE_SUBMIT_CHECK))){
            flag = true;
        }
        return flag;
    }
    //验证频率
    private boolean checkSmsCode(String phone,String codeType){
        boolean flag=false;
        //1.拼接前缀，拿到一个key
        String key= RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_SMS,codeType,phone);
        //2.通过这个key去redis中查询
        String result = redisUtils.getValue(key);
        //3.redis中不存在，说明过了有效期，可以发送
        if (StringUtils.isBlank(result)){
            flag = true;
        }
        return  flag;
    }
}


